package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private ITravelCommentRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public TravelComment save(TravelComment comment) {
        //如果是评论的评论, 需要维护引入对象
        String refId = comment.getRefComment().getId();
        if(StringUtils.hasLength(refId)){
            //此时评论的评论
            TravelComment ref = repository.findById(refId).get();
            comment.setRefComment(ref);
        }
        //如果是普通评论
        repository.save(comment);

        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //select * from strategeComment where detailId = 1 order by ... limit...
        //拼接条件
        Query query = new Query();
        if(qo.getTravelId() != -1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
       //查总数
        Long  count = mongoTemplate.count(query, TravelComment.class);
        if(count == 0){
            return Page.empty();  //空分页对象
        }
        //需要进行分页信息的设置
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(sort);
        //查询当前页的list集合: 当前页数据
        List<TravelComment> list =  mongoTemplate.find(query, TravelComment.class);

        //分页相关信息对象
        return new PageImpl(list, pageable, count);
    }

    @Override
    public Long getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return  mongoTemplate.count(query, TravelComment.class);
    }
}
